package com.lt.lumentracks.aspect;

import com.alibaba.fastjson.JSONObject;
import com.lt.lumentracks.annotation.LogIp;
import com.lt.lumentracks.utils.IpUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class IpLogAspect {

    @Autowired
    private IpUtils ipUtils;
    private static final Logger log = LoggerFactory.getLogger(IpLogAspect.class);
    private static final String exampleResponse = """
           {
              "status": "0",
              "t": "",
              "set_cache_time": "",
              "data": [
                {
                  "ExtendedLocation": "",
                  "OriginQuery": "120.236.XXX.XXX",
                  "SchemaVer": "",
                  "appinfo": "",
                  "disp_type": 0,
                  "fetchkey": "120.236.XXX.XXX",
                  "location": "广东省广州市 移动",
                  "origip": "120.236.XXX.XXX",
                  "origipquery": "120.236.XXX.XXX",
                  "resourceid": "6006",
                  "role_id": 0,
                  "schemaID": "",
                  "shareImage": 1,
                  "showLikeShare": 1,
                  "showlamp": "1",
                  "strategyData": {

                  },
                  "titlecont": "IP地址查询",
                  "tplt": "ip"
                }
              ]
           }
          """;



    @Before("@annotation(logIp)") // 拦截所有带有 @LogIp 注解的方法，并且将注解对象作为参数logIp传递到通知方法中
    public void doBefore(JoinPoint jp, LogIp logIp) {
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
                        .getRequest();

        String ip = ipUtils.getClientIpAddress(request); // 1.获取客户端IP
        String method = jp.getSignature().toShortString(); // 2.从JoinPoint对象中获取被拦截方法的简短签名

        String jsonStr = ipUtils.parseIpAddress(ip); // 3.解析IP地址（解析响应可以看上面的 exampleResponse ）
        JSONObject jo = JSONObject.parseObject(jsonStr);
        String location = "未知";
        if ("0".equals(jo.getString("status")) && !jo.getJSONArray("data").isEmpty()) {
            location = jo.getJSONArray("data")
                    .getJSONObject(0)
                    .getString("location");
        }

        log.info(">>>> 方法{} 被 IP: {} 调用，地理位置为：{}", method, ip, location);

        // 这里可以写数据库、写 Redis、发消息队列等
    }

}